package com.apps.ftapp.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.LessonDetailAdapter;
import com.apps.ftapp.adapter.MyAdapterLesson;
import com.apps.ftapp.model.LessonDetailItemModel;
import com.apps.ftapp.model.PreOrderModel;
import com.apps.ftapp.model.Queding;
import com.apps.ftapp.model.SubjectDetailModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.DensityUtils;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.ScreenUtils;
import com.apps.ftapp.util.Tools;
import com.apps.ftapp.view.NoScrollListView;
import com.bumptech.glide.Glide;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;

public class LessonDetailActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.dool)
    TextView dool;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.sale_num_tit)
    TextView saleNumTit;
    @BindView(R.id.sale_num)
    TextView saleNum;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.lesson_title)
    TextView lessonTitle;
    @BindView(R.id.lesson_time)
    TextView lessonTime;
    @BindView(android.R.id.tabs)
    TabWidget tabs;
    @BindView(android.R.id.tabcontent)
    FrameLayout tabcontent;
    @BindView(R.id.tabhost)
    TabHost tabHost;
    @BindView(R.id.shixue)
    TextView shixue;
    @BindView(R.id.lijigoumai)
    TextView lijigoumai;
    @BindView(R.id.yigou)
    TextView yigou;
    @BindView(R.id.topImg)
    ImageView topImg;
    @BindView(R.id.edit_user_info)
    TextView editUserInfo;
    @BindView(R.id.lesson_container)
    RelativeLayout lessonContainer;

    private SubjectDetailModel result;

    @SuppressLint("ResourceType")
    @IdRes
    int TAG1401 = 1000;

    @SuppressLint("ResourceType")
    @IdRes
    int TAG1402 = 1001;

    @SuppressLint("ResourceType")
    @IdRes
    int TAG1403 = 1002;

    private WebView webView1;
    private NoScrollListView listView2;
    private WebView webView3;

    private List<LessonDetailItemModel> lists = new ArrayList<>();
    private LessonDetailAdapter lessonDetailAdapter;

    private Gson gson = new Gson();
    String id = "";
    String title = "";
    String mytitle = "";
    String inviteId = "";
    String type;//normal 点播棵 live 直播课

    private CustomPopWindow mListPopWindow;

    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;
    private BaseBottomDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson_detail);
        ButterKnife.bind(this);

        ShareSDK.initSDK(this);
//        setTitle("课程详情");

        //显示图片的配置  
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        id = bundle.getString("id");
        mytitle = bundle.getString("mytitle");
        inviteId = bundle.getString("inviteId");
        type = bundle.getString("type");
        try {
            title = bundle.getString("title");
        } catch (Exception e) {
            title = "课程详情";
        }

        L.i("main", id + "===" + inviteId + "===" + mytitle);

        setTitle(title);


        ViewGroup.LayoutParams params = topImg.getLayoutParams();

        params.height = (int) (((DensityUtils.dp2px(LessonDetailActivity.this, (Constant.SCREEN_WIDTH)) * 0.56)));
        topImg.setLayoutParams(params);

        lijigoumai.setOnClickListener(this);
        shixue.setOnClickListener(this);
        shareBtn.setVisibility(View.VISIBLE);
        shareBtn.setOnClickListener(this);
        editUserInfo.setOnClickListener(this);

        initView();

        loadData(id);


    }

    private void initView() {

        tabHost.setup();
        // 方法3使用，动态载入xml，不需要Activity
        View view1 = LayoutInflater.from(this).inflate(R.layout.activity_lesson_detail_item1, tabHost.getTabContentView());
        View view2 = LayoutInflater.from(this).inflate(R.layout.activity_lesson_detail_item2, tabHost.getTabContentView());
        View view3 = LayoutInflater.from(this).inflate(R.layout.activity_lesson_detail_item3, tabHost.getTabContentView());

        //
        webView1 = view1.findViewById(R.id.webView1);
        listView2 = view2.findViewById(R.id.listView);
        webView3 = view3.findViewById(R.id.webView3);




        /* 以上创建和添加标签页也可以用如下代码实现 */
        //tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(composeLayout("课程简介", TAG1401, R.drawable.lesson_tab_image)).setContent(R.id.lesson_item01));
        //tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator(composeLayout("课程表", TAG1402, R.drawable.lesson_tab_image)).setContent(R.id.lesson_item02));
        //tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator(composeLayout("购买需知", TAG1403, R.drawable.lesson_tab_image)).setContent(R.id.lesson_item03));
        composeLayout("课程简介", TAG1401, 1);
        composeLayout("课程表", TAG1402, 2);
        composeLayout("课程须知", TAG1403, 3);

        View v = tabHost.getChildAt(0);
        TextView textView = v.findViewById(TAG1401);
        textView.setTextColor(Color.parseColor("#37C000"));
        //标签切换事件处理，setOnTabChangedListener
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            // tabId是newTabSpec第一个参数设置的tab页名，并不是layout里面的标识符id
            public void onTabChanged(String tabId) {
                if (tabId.equals("tab1")) {   //第一个标签
                    View v = tabHost.getChildAt(0);
//                    v.setTextColor(Color.parseColor("#999999"));
                    settabView(v);


                    TextView textView = v.findViewById(TAG1401);
                    textView.setTextColor(Color.parseColor("#37C000"));


                }
                if (tabId.equals("tab2")) {   //第二个标签

                    View v = tabHost.getTabWidget().getChildAt(1);
                    settabView(v);

                    TextView textView = v.findViewById(TAG1402);
                    textView.setTextColor(Color.parseColor("#37C000"));

                    //   Toast.makeText(LessonDetailActivity.this, "点击标签页二", Toast.LENGTH_SHORT).show();
                }
                if (tabId.equals("tab3")) {   //第三个标签
                    View v = tabHost.getTabWidget().getChildAt(2);
                    settabView(v);
                    TextView textView = v.findViewById(TAG1403);
                    textView.setTextColor(Color.parseColor("#37C000"));
                }
            }
        });


    }


    void settabView(View v) {
        View v1 = tabHost.getTabWidget().getChildAt(0);
        TextView textView1 = v1.findViewById(TAG1401);
        textView1.setTextColor(Color.parseColor("#999999"));
        View v2 = tabHost.getTabWidget().getChildAt(1);
        TextView textView2 = v2.findViewById(TAG1402);
        textView2.setTextColor(Color.parseColor("#999999"));
        View v3 = tabHost.getTabWidget().getChildAt(2);
        TextView textView3 = v3.findViewById(TAG1403);
        textView3.setTextColor(Color.parseColor("#999999"));


    }


    /**
     * TODO set listviews height
     *
     * @param listView
     * @param listAdapter
     */
    public void setListViewHeightBasedOnChildren(ListView listView,
                                                 Adapter listAdapter) {

        listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) + 100;

        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);

        listView.setLayoutParams(params);
    }


//
//    /**
//     * 更新Tab标签的颜色，和字体的颜色
//     * @param tabHost
//     */
//    private void updateTab(final TabHost tabHost) {
//        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
//            View view = tabHost.getTabWidget().getChildAt(i);
//            TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
//            tv.setTextSize(16);
//            if (tabHost.getCurrentTab() == i) {//选中
//                view.setBackgroundDrawable(getResources().getDrawable(R.drawable.lvsexiajiantou));//选中后的背景
//                tv.setTextColor(this.getResources().getColorStateList(
//                        android.R.color.black));
//            } else {//不选中
//                view.setBackgroundDrawable(getResources().getDrawable(R.drawable.f_arrow1));//非选择的背景
//                tv.setTextColor(this.getResources().getColorStateList(
//                        android.R.color.white));
//            }
//        }
//    }

    public void composeLayout(String s, int id, int i) {
        LayoutInflater inflater = this.getLayoutInflater();
        View view = inflater.inflate(R.layout.lesson_host, null);
        TextView textView = view.findViewById(R.id.name);
        textView.setId(id);
        textView.setText(s);
        TabHost.TabSpec spec = tabHost.newTabSpec("tab" + i);
        spec.setIndicator(view);
        if (i == 1) {
            spec.setContent(R.id.lesson_item01);
        } else if (i == 2) {
            spec.setContent(R.id.lesson_item02);
        } else if (i == 3) {
            spec.setContent(R.id.lesson_item03);
        }
        tabHost.addTab(spec);


//        // 定义一个LinearLayout布局
//        RelativeLayout mainlayout = new RelativeLayout(this);
//        LinearLayout layout = new LinearLayout(this);
//        layout.setGravity(Gravity.CENTER);
//        // 设置布局显示
//        layout.setOrientation(LinearLayout.HORIZONTAL);
//
//        // 定义TextView
//        TextView tv = new TextView(this);
//        tv.setGravity(Gravity.CENTER);
//        tv.setSingleLine(true);
//        tv.setText(s);
//        tv.setId(id);
////        tv.setBackgroundResource(R.drawable.lesson_tab_text);
//        tv.setTextColor(Color.parseColor("#999999"));
//        tv.setTextSize(14);
//        layout.addView(tv, new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.WRAP_CONTENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT));
//
//        //
//        ImageView iv = new ImageView(this);
//        iv.setImageResource(i);
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.WRAP_CONTENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT);
//        lp.gravity = Gravity.CENTER;
//        iv.setLayoutParams(lp);
//        layout.addView(iv);
//        mainlayout.addView(layout);
//        return mainlayout;
    }

    private void loadData(String id) {

        ///course/info
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        L.i("main", "id:" + id + "::" + Constant.token + "::::" + Constant.uid);
        Async.post("course/info", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, final byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    result = gson.fromJson(new String(responseBody), SubjectDetailModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        lessonTitle.setText(result.getData().getCourse().getTitle());
                        lessonTime.setText(result.getData().getCourse().getNew_startTime() + "-" + result.getData().getCourse().getNew_endTime());


                        price.setText(result.getData().getCourse().getPrice());
                        yigou.setText("已购");
                        saleNum.setText(result.getData().getCourse().getStudentNum() + "");
                        saleNumTit.setText(" 限购" + result.getData().getCourse().getMaxStudentNum());
                        time.setText(result.getData().getCourse().getNew_endShopTime() + " " + "停售");

                        L.i("main", ">>>>" + result.getData().getLesson());
                        webView1.loadData(result.getData().getCourse().getAbout(), "text/html; charset=UTF-8", null);
                        webView3.loadData(result.getData().getCourse().getQuestion(), "text/html; charset=UTF-8", null);


                        editUserInfo.setText(result.getData().getCourse().getShare_icon());

                        Glide.with(getApplicationContext()).load(result.getData().getCourse().getLargePicture())
                                .into((ImageView) findViewById(R.id.topImg));


//                        imageLoader.displayImage(result.getData().getCourse().getLargePicture(),topImg,options);
//                        topImg.set
                        //数组 shixue shixue[if]为1则代表有试学 0则没有 来控制是否显示试学按钮 shixue[lesson]为试学列表
                        // （其中type 为状态 live 直播；video 录播,weikaike未开课 未开课时点击提示wkktext。直播和回放分别根据roomId进入不同的页面）
                        if (result.getShixue() != null && Tools.isNull(result.getShixue().getIfX()).equals("1")) {

                            shixue.setVisibility(View.VISIBLE);

                        }


                        //是否已买
                        if (null != result.getYimai() && Tools.isNull(result.getYimai().getIfX()).equals("1")) {
                            lijigoumai.setText(result.getYimai().getButton());
                            //f
                        } else {
                            //是否已停售
                            if ("1".equals(Tools.isNull(result.getTingshou().getIfX()))) {
                                lijigoumai.setText(result.getTingshou().getButton());
                                lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
                            } else {
                                //是否报满
                                if (Tools.isNull(result.getBaoman().getIfX()).equals("1")) {
                                    lijigoumai.setText(result.getBaoman().getButton());
                                    lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
                                } else {//是否免费
                                    if (Tools.isNull(result.getMianfei().getIfX()).equals("1")) {
                                        lijigoumai.setText(result.getMianfei().getButton());
                                    }
                                }

                            }


//                        //
//                        if("0.00".equals(Tools.isNull(result.getData().getCourse().getPrice()))||"0.0".equals(Tools.isNull(result.getData().getCourse().getPrice()))){
//                            shixue.setVisibility(View.GONE);
//                            lijigoumai.setText("立即观看");
//                        }else{
//                            //是否已买
//                            if(null!=result.getYimai()&&Tools.isNull(result.getYimai().getIfX()).equals("1")){
//                                lijigoumai.setText(result.getYimai().getButton());
//                                //f
//                            }else{
//                                //是否已停售
//                                if("1".equals(Tools.isNull(result.getTingshou().getIfX()))){
//                                    lijigoumai.setText(result.getTingshou().getButton());
//                                    lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
//                                }else{
//                                    //是否
//                                    if(Tools.isNull(result.getBaoman().getIfX()).equals("1")){
//                                        lijigoumai.setText(result.getBaoman().getButton());
//                                        lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
//                                    }else{
//                                        if(Tools.isNull(result.getMianfei().getIfX()).equals("1")){
//                                            lijigoumai.setText(result.getMianfei().getButton());
//                                        }
//                                    }
//
//                                }
//                            }
                        }


//                        if(Tools.isNull(result.getBaoman().getIfX()).equals("1")){
//                            lijigoumai.setText(result.getBaoman().getButton());
//                        }
//                        if(Tools.isNull(result.getMianfei().getIfX()).equals("1")){
//                            lijigoumai.setText(result.getMianfei().getButton());
//                        }


//                        int height = 0;
//                        List<LessonDetailItemModel> dlist = new ArrayList<LessonDetailItemModel>();
                        if (null != result.getData().getLesson() && result.getData().getLesson().size() > 0) {
                            for (int i = 0; i < result.getData().getLesson().size(); i++) {
                                L.i("main" + "--------------lists---------------------------");
                                SubjectDetailModel.DataBean.LessonBean m = result.getData().getLesson().get(i);
                                LessonDetailItemModel model = new LessonDetailItemModel();
                                model.setId(Tools.isNull(m.getId()));
                                model.setTitle(Tools.isNull(m.getTitle()));
                                model.setStartTime(m.getNew_startTime());
                                model.setEndTime(m.getNew_endTime());
                                model.setYimai(result.getYimai().getIfX());
                                model.setRoomId(Tools.isNull(m.getRoomId()));
                                model.setType(Tools.isNull(m.getType()));
                                if (null != result.getShixue()) {
                                    model.setShixue(result.getShixue().getIfX() + "");
                                } else {
                                    model.setShixue("0");
                                }

                                lists.add(model);
                            }
                        }

//                        L.i("main","高度哦::"+height);
                        lessonDetailAdapter = new LessonDetailAdapter(getApplicationContext(), lists, result.getData().getCourse().getType());
//                        lessonDetailAdapter.addRes(lists);
                        listView2.setAdapter(lessonDetailAdapter);

                        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (null != result.getYimai() && Tools.isNull(result.getYimai().getIfX()).equals("1")) {
                                    updatelesson(result.getData().getCourse(), lists.get(position));
                                } else {
                                    Toasty.normal(getApplicationContext(), "请先购买课程").show();
                                }
                            }
                        });

                        setListViewHeightBasedOnChildren(listView2, lessonDetailAdapter);

//                        ViewGroup.LayoutParams params = listView2.getLayoutParams();
//                        params.height = height;


                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.lijigoumai:

                //已买
//                if (null != result.getYimai() && Tools.isNull(result.getYimai().getIfX()).equals("1")) {
                if (null != result.getYimai() && Tools.isNull(result.getYimai().getIfX()).equals("1")) {
                    L.i("main", "已买。。。。。。");
                    lijigoumai.setText(result.getYimai().getButton());
                    try {
//                        Intent intent = new Intent(getApplicationContext(), DefPlaybackActivity.class);
//                        intent.putExtra("appKey", Constant.APPKEY);
//                        intent.putExtra("nickname", "我爱为师");
//                        intent.putExtra("partner", Constant.PID);
//                        intent.putExtra("roomId", result.getData().getLesson().get(0).getRoomId());
//                        intent.putExtra("uid", Constant.uid);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                        getApplicationContext().startActivity(intent);

//                        Intent intent = new Intent(getApplicationContext(), DefPlaybackActivity.class);
////                        Intent intent = new Intent(getApplicationContext(), DBOnlineActivity.class);
//                        intent.putExtra("appKey", Constant.APPKEY);
//                        intent.putExtra("nickname",Tools.isNull(Constant.nickname).equals("")?"爱为师总师":Constant.nickname);
//                        intent.putExtra("partner", Constant.PID);
//                        intent.putExtra("roomId", result.getData().getLesson().get(0).getRoomId());
//                        intent.putExtra("uid", Constant.uid);
//                        intent.putExtra("title", result.getData().getLesson().get(0).getTitle());
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                        getApplicationContext().startActivity(intent);


                        HashMap map = new HashMap();
                        map.put("id", result.getData().getCourse().getId());
                        map.put("title", result.getData().getCourse().getTitle());
                        map.put("type", result.getData().getCourse().getType());
                        ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, MyLessonListActivity.class, map);
//                        ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, MyLessonActivity.class,false);


                    } catch (Exception e) {
                    }
                } else {
                    //是否已停售
                    if ("1".equals(Tools.isNull(result.getTingshou().getIfX()))) {
                        lijigoumai.setText(result.getTingshou().getButton());
                        lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
                    } else {
                        //是否报满
                        if (Tools.isNull(result.getBaoman().getIfX()).equals("1")) {
                            lijigoumai.setText(result.getBaoman().getButton());
                            lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
                        } else {//是否免费
                            if (Tools.isNull(result.getMianfei().getIfX()).equals("1")) {
                                lijigoumai.setText(result.getMianfei().getButton());
                                //
                                buy(result.getData().getCourse().getId());

                            } else {
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("id", result.getData().getCourse().getId());
                                map.put("icon", result.getData().getCourse().getLargePicture());
                                map.put("price", result.getData().getCourse().getPrice());
                                map.put("title", result.getData().getCourse().getTitle());
                                map.put("desc", "已购" + result.getData().getCourse().getStudentNum() + "/限购" + result.getData().getCourse().getMaxStudentNum());
                                map.put("endShopTime", result.getData().getCourse().getNew_endShopTime());
                                ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, OrderAddActivity.class, map);

                            }
                        }

                    }


//
//                if(Tools.isNull(result.getYimai().getIfX()).equals("1")){
//                    lijigoumai.setText(result.getYimai().getButton());
//                   try {
//                       Intent intent = new Intent(getApplicationContext(), DefPlaybackActivity.class);
//                       intent.putExtra("appKey", Constant.APPKEY);
//                       intent.putExtra("nickname", "我爱为师");
//                       intent.putExtra("partner", Constant.PID);
//                       intent.putExtra("roomId", result.getData().getLesson().get(0).getRoomId());
//                       intent.putExtra("uid", Constant.uid);
//                       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                       getApplicationContext().startActivity(intent);
//                   }catch (Exception e){}
//
//                    //f
//                }else{
//                    if("1".equals(Tools.isNull(result.getTingshou().getIfX()))){
//                        lijigoumai.setText(result.getTingshou().getButton());
//                        lijigoumai.setBackgroundColor(Color.parseColor("#cccccc"));
//                    }else{
//
//                        if(Tools.isNull(result.getBaoman().getIfX()).equals("1")){
//                            lijigoumai.setText(result.getBaoman().getButton());
////                            ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, MyLessonActivity.class,false);
//
//                        }else{
//                            if(Tools.isNull(result.getMianfei().getIfX()).equals("1")){
//                                lijigoumai.setText(result.getMianfei().getButton());
//                                ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, MyLessonActivity.class,false);
//
//                            }else{
//
//                                //购买
//
//                                HashMap<String,Object> map = new HashMap<>();
//                                map.put("id",result.getData().getCourse().getId());
//                                map.put("icon",result.getData().getCourse().getLargePicture());
//                                map.put("price",result.getData().getCourse().getPrice());
//                                map.put("title",result.getData().getCourse().getTitle());
//                                map.put("type","");
//                                ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, OrderAddActivity.class,map);
//
//
//                            }
//                        }
//
//                    }
                }

                //
//                if(Tools.isNull(result.getYimai().getIfX()).equals("1")||"0.00".equals(Tools.isNull(result.getData().getCourse().getPrice()))||"0.0".equals(Tools.isNull(result.getData().getCourse().getPrice()))) {
//
//                    ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, MyLessonActivity.class,false);
//                }else{
//
//                    //如果买过
//
//
//                    if("0".equals(Tools.isNull(result.getTingshou()))){
//                        HashMap<String,Object> map = new HashMap<>();
//                        map.put("id",result.getData().getCourse().getId());
//                        map.put("icon",result.getData().getCourse().getLargePicture());
//                        map.put("price",result.getData().getCourse().getPrice());
//                        map.put("title",result.getData().getCourse().getTitle());
//                        ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, OrderAddActivity.class,map);
//                    }
//
//
//
//                }


                break;

            case R.id.shixue:
                showPopListView();
                break;

            case R.id.shareBtn:

                share();

                break;


            case R.id.edit_user_info:


                share();

                break;

        }
    }

    private void buy(String id) {
        L.i("main", "购买。。。。。");
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("id", id);
        params.put("targetType", "course");
        Async.post("course/buy", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", ">>>>>" + new String(responseBody));
                    PreOrderModel jsonBean = gson.fromJson(new String(responseBody), PreOrderModel.class);
                    if (1 == Tools.isIntNull(jsonBean.getSuccess())) {

                        ActivitySkipUtil.skipAnotherActivity(LessonDetailActivity.this, MyLessonActivity.class, false);
                    } else {
                        Toasty.normal(getApplicationContext(), jsonBean.getError()).show();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });


    }

    private void showPopListView() {
        L.i("main", "-----------------------------");
        BottomDialog.create(getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {      // 可以进行一些必要对View的操作
                    @Override
                    public void bindView(View v) {
                        // you can do bind view operation
                        if (null != result.getShixue()) {
                            handleListView(v);
                        }

                        // you can do bind view operation
                    }
                })
                .setHeight(ScreenUtils.getScreenHeight(getApplicationContext()) / 3)
                .setLayoutRes(R.layout.pop_list)      // dialog layout
                .show();

//        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_list, null);//处理popWindow 显示内容
//        handleListView(contentView);        //创建并显示popWindow
//        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
//                .setView(contentView)
//                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
//                .setBgDarkAlpha(0.7f) // 控制亮度
////                .size(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
//                .size(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.getScreenHeight(getApplicationContext())/3)//显示大小
//                .create()
//                .showAsDropDown(shixue, 0, 80);

    }

    private void handleListView(View contentView) {
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(manager);
        MyAdapterLesson adapter = new MyAdapterLesson();
        adapter.setData(mockData(), getApplicationContext());
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }


    private List<Map<String, Object>> mockData() {
        List<Map<String, Object>> data = new ArrayList<>();
        if (null != result.getShixue().getLesson() && result.getShixue().getLesson().size() > 0) {
            for (SubjectDetailModel.ShixueBean.LessonBeanX s : result.getShixue().getLesson()) {
                Map m = new HashMap();
                m.put("id", s.getId());
                m.put("title", s.getTitle());
                m.put("roomId", s.getRoomId());
                m.put("type", result.getData().getCourse().getType());
                m.put("times", s.getNew_startTime() + "至" + s.getNew_endTime());
                data.add(m);
            }
        }
        return data;
    }


    private void share() {
        dialog = BottomDialog.create(getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        // // You can do any of the necessary the operation with the view

                        TextView share_title = v.findViewById(R.id.share_title);
                        share_title.setText(result.getData().getCourse().getShare_icon());
                        TextView share_desc = v.findViewById(R.id.share_desc);
                        share_desc.setText(result.getData().getCourse().getShare_desc());


                        TextView weixin = v.findViewById(R.id.weixin);
                        weixin.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                share(0);
                            }
                        });
                        TextView qq = v.findViewById(R.id.qq);
                        qq.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                share(2);
                            }
                        });
                        TextView qqkongjian = v.findViewById(R.id.qqkongjian);
                        qqkongjian.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                share(3);
                            }
                        });
                        TextView pengyouquan = v.findViewById(R.id.pengyouquan);

                        pengyouquan.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                share(1);
                            }
                        });

                        TextView share_cancle = v.findViewById(R.id.share_cancle);
                        share_cancle.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setLayoutRes(R.layout.custom_share_view)
                .setDimAmount(0.1f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("分享赚钱")     // setting the DialogFragment tag
                .show();

//        dialog.dismiss();


//        View dialogView = LayoutInflater.from(this).inflate(R.layout.custom_share_view, null);
//        TextView share_title = (TextView) dialogView.findViewById(R.id.share_title);
//        share_title.setText(result.getData().getCourse().getShare_icon());
//        TextView share_desc = (TextView) dialogView.findViewById(R.id.share_desc);
//        share_desc.setText(result.getData().getCourse().getShare_desc());
//
//        ShareBottomPopupDialog shareBottomPopupDialog = new ShareBottomPopupDialog(this, dialogView);
//        shareBottomPopupDialog.showPopup(lessonContainer);
//        SubjectDetailModel.DataBean.CourseBean.ShareBean shareBean = result.getData().getCourse().getShare();
//        if (null != shareBean) {
//            OnekeyShare oks = new OnekeyShare();
//            oks.disableSSOWhenAuthorize();
//            oks.setTitle(shareBean.getTitle());
//            oks.setTitleUrl(shareBean.getUrl());
//            oks.setText(shareBean.getTitle());
//            oks.setImageUrl(shareBean.getImage());
//            oks.setUrl(shareBean.getUrl());
//            oks.setSite(shareBean.getTitle());
//            oks.setSiteUrl(shareBean.getUrl());
//            oks.show(LessonDetailActivity.this);
//        }
    }


    public void share(int state) {
        SubjectDetailModel.DataBean.CourseBean.ShareBean shareBean = result.getData().getCourse().getShare();
        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();
        oks.setTitleUrl(shareBean.getUrl());
        oks.setText(shareBean.getTitle());
        oks.setImageUrl(shareBean.getImage());
        oks.setUrl(shareBean.getUrl());
        oks.setSite(shareBean.getTitle());
        oks.setSiteUrl(shareBean.getUrl());
        oks.setTitle(shareBean.getTitle());
        switch (state) {
            case 0:
//                oks.setTitle("分享到微信");

                zhixing(result.getData().getCourse().getId(), "分享到微信");
                oks.setPlatform(Wechat.NAME);
                break;

            case 1:
//                oks.setTitle("分享到朋友圈");
                zhixing(result.getData().getCourse().getId(), "分享到朋友圈");
                oks.setPlatform(WechatMoments.NAME);
                break;

            case 2:
                zhixing(result.getData().getCourse().getId(), "分享到QQ");
//                oks.setTitle("分享到QQ");
                oks.setPlatform(QQ.NAME);
                break;

            case 3:
                zhixing(result.getData().getCourse().getId(), "分享到QQ空间");
//                oks.setTitle("分享到QQ空间");
                oks.setPlatform(QZone.NAME);
                break;
        }

        oks.show(LessonDetailActivity.this);


    }


    public void zhixing(String id, String content) {

        RequestParams params = new RequestParams();
        params.put("userId", Constant.uid);
        params.put("token", Constant.token);
        params.put("id", id + "");
        params.put("mytitle", content + "");
        Async.post("course/share/name", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody) + "......");
                    Queding result = gson.fromJson(new String(responseBody), Queding.class);
                    if (Tools.isIntNull(result.getSuccess()) == 1) {


                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }

    private void updatelesson(final SubjectDetailModel.DataBean.CourseBean temp, final LessonDetailItemModel lesson) {

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("lid", lesson.getId());
        Async.post("my/courseskan", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    Queding result = gson.fromJson(new String(responseBody), Queding.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        Intent intent = null;
                        if ("live".equals(lesson.getType())) {
                            intent = new Intent(getApplicationContext(), CustomizedLiveActivity.class);
                        } else {
                            intent = new Intent(getApplicationContext(), CusomizedPlayBackActivity.class);
                        }
                        if (type.equals("normal")) {
                            intent = new Intent(getApplicationContext(), DefPlaybackActivity.class);
                        }
                        //intent = new Intent(getApplicationContext(), DefPlaybackActivity.class);

                        intent.putExtra("appKey", Constant.APPKEY);
                        intent.putExtra("nickname", Tools.isNull(Constant.nickname).equals("") ? "未知用户" : Constant.nickname);
                        intent.putExtra("partner", Constant.PID);
                        intent.putExtra("roomId", lesson.getRoomId());
                        intent.putExtra("uid", Constant.uid);
                        intent.putExtra("title", lesson.getTitle());
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        getApplicationContext().startActivity(intent);
                    } else {
                        return;
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                L.i("main", ">>>>>" + new String(responseBody));

            }
        });
    }
}
